<?php

namespace app\api\controller;


use app\common\traits\ApiTrait;
use support\Request;
use support\Response;
use think\facade\Db;

class DashboardController
{
    use ApiTrait;

    protected $noNeedLogin = ['index', 'info', 'getUrl', 'getLine'];

    /**
     * 数据大屏
     * @param Request $request
     * @return Response
     */
    public function index(Request $request) : Response {
        return view();
    }

    /**
     * 数据来源
     * @param Request $request
     * @return Response
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(Request $request) : Response
    {
        // 解码获得活动 ID
        $activityId = base64_decode(urldecode(input('code')));

        // 获取活动数据
        $data = Db::name('activity')->where(['id' => $activityId])->find();
        if (empty($data)) return $this->reError('该活动不存在');

        // 获取所有员工数据
        $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $activityId, 'role' => 2])->column('user_id');

        return $this->reSuccess('成功', [
            'data' => [
                // 活动标题
                'activity_title' => $data['activity_title'],
                // 倒计时
                'countdown' => strtotime($data['activity_end_time']),
                // 成交金额
                'transaction_amount' => Db::name('order')->where(['activity_id' => $activityId, 'order_status' => 2])->sum('total_price'),
                // 曝光次数
                'total_visitor_num' => $data['visitor_num'],
                // 获客总数
                'total_join_num' => $data['join_num'],
                // 翻牌礼品
                'total_activity_prize' => Db::name('payment_activity_prize')->where(['activity_id' => $activityId])->count(),
                // 盲盒礼品
                'total_box_prize' => Db::name('payment_platform_box')->where(['activity_id' => $activityId])->count(),
                // 成交客户
                'payment_user_num' => Db::name('order')->where(['activity_id' => $activityId, 'order_status' => 2])->group('user_id')->count(),
                // 报名人数 (待支付 + 已支付的订单）
                'participate_num' => Db::name('order')->where([['activity_id', '=', $activityId], ['order_status', '<>', 0]])->group('user_id')->count(),
                // 成交订单
                'payment_money_num' => Db::name('order')->where(['activity_id' => $activityId, 'order_status' => 2])->group('user_id')->count(),
                // 奖励金额
                'total_disburse' => Db::name('payment_disburse')->where(['activity_id' => $activityId])->sum('amount'),
                // 正在报名 (待支付）
                'participate_ongoing_num' => Db::name('order')->where([['activity_id', '=', $activityId], ['order_status', '=', 1]])->where('user_id', 'not in', $clerk_user_ids)->group('user_id')->count(),
            ],
            // 最近报名（已支付的订单）
            'payment_order' => Db::name('order')
                ->alias('o')
                ->join('user u', 'u.id = o.user_id', 'left')
                ->join('user parent', 'parent.id = o.recom_user_id', 'left')
                ->where(['o.activity_id' => $activityId, 'o.order_status' => 2])
                ->where('o.user_id', 'not in', $clerk_user_ids)
                ->field('u.*, parent.nickname as recom_nickname, o.name, o.phone, o.create_time')
                ->limit(100)
                ->order('o.id desc')
                ->select()
                ->toArray(),
            // 正在报名（待支付的订单）
            'participate_order' => Db::name('order')
                ->alias('o')
                ->join('user u', 'u.id = o.user_id', 'left')
                ->join('user parent', 'parent.id = o.recom_user_id', 'left')
                ->join('user clerk', 'clerk.id = o.clerk_user_id', 'left')
                ->where(['o.activity_id' => $activityId, 'o.order_status' => 1])
                ->where('o.user_id', 'not in', $clerk_user_ids)
                ->field('u.*, parent.nickname as recom_nickname, o.name, o.phone, clerk.nickname as clerk_nickname')
                ->limit(100)
                ->order('o.create_time desc')
                ->select()
                ->toArray(),
            // 员工拓客排行榜
            'staff_rankings' => Db::query("
                SELECT 
                    t1.user_id,
                    u.avatar_url,
                    u.nickname,
                    COALESCE(t2.total_recomm, 0) as total_recomm,
                    COALESCE(t3.total_orders, 0) as total_orders
                FROM 
                    tuoke_activity_user_role t1
                    LEFT JOIN (
                        SELECT 
                            recom_user_id,
                            COUNT(*) as total_recomm
                        FROM 
                            tuoke_order
                        WHERE 
                            activity_id = {$activityId}
                        GROUP BY 
                            recom_user_id
                    ) t2 ON t1.user_id = t2.recom_user_id
                    LEFT JOIN (
                        SELECT 
                            recom_user_id,
                            COUNT(*) as total_orders
                        FROM 
                            tuoke_order
                        WHERE 
                            activity_id = {$activityId}
                            AND order_status = 2
                        GROUP BY 
                            recom_user_id
                    ) t3 ON t1.user_id = t3.recom_user_id
                    LEFT JOIN tuoke_user u ON u.id = t1.user_id
                WHERE 
                    t1.activity_id = {$activityId} 
                    AND t1.role = 2
                ORDER BY 
                    total_recomm DESC,
                    total_orders DESC;
                "),
            // 盲盒抽奖（最近获得的盲盒记录）
            'platform_box_prize' => Db::name('payment_platform_box')
                ->alias('pb')
                ->join('user u', 'u.id = pb.user_id', 'left')
                ->join('order o', 'o.id = pb.order_id', 'left')
                ->where(['pb.activity_id' => $activityId])
                ->field('u.*, pb.prize_name, o.name, o.phone')
                ->limit(100)
                ->select()
                ->toArray(),
        ]);
    }

    /**
     * 今日数据趋势
     * @param Request $request
     * @return Response
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLine(Request $request) : Response
    {
        // 解码获得活动 ID
        $activityId = base64_decode(urldecode(input('code')));
        
        // 获取活动数据
        $data = Db::name('activity')->where(['id' => $activityId])->find();
        if (empty($data)) return $this->reError('该活动不存在');
        
        // 获取所有员工数据
        $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $activityId, 'role' => 2])->column('user_id');
        
        // 获取今天的开始时间和结束时间
        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');
        
        // 获取今天的小时数据
        $hours = [];
        for ($i = 0; $i < 24; $i++) {
            $hours[] = sprintf('%02d:00', $i);
        }
        
        // 初始化数据
        $visitor_data = array_fill(0, 24, 0); // 曝光次数
        $join_data = array_fill(0, 24, 0);    // 获客总数
        $participate_data = array_fill(0, 24, 0); // 报名人数
        $payment_data = array_fill(0, 24, 0); // 成交人数
        
        // 获取曝光次数数据
        $visitor_logs = Db::name('activity_operation_log')
            ->where([
                ['activity_id', '=', $activityId],
                ['type', '=', 2], // 浏览量
                ['create_time', '>=', $today_start],
                ['create_time', '<=', $today_end]
            ])
            ->select()
            ->toArray();
        
        foreach ($visitor_logs as $log) {
            $hour = (int)date('H', strtotime($log['create_time']));
            $visitor_data[$hour]++;
        }
        
        // 获取获客总数数据
        $join_logs = Db::name('order')
            ->where([
                ['activity_id', '=', $activityId],
                ['create_time', '>=', $today_start],
                ['create_time', '<=', $today_end]
            ])
            ->where('user_id', 'not in', $clerk_user_ids)
            ->select()
            ->toArray();
        
        foreach ($join_logs as $log) {
            $hour = (int)date('H', strtotime($log['create_time']));
            $join_data[$hour]++;
        }
        
        // 获取报名人数数据
        $participate_logs = Db::name('order')
            ->where([
                ['activity_id', '=', $activityId],
                ['order_status', '<>', 0], // 非预生成订单
                ['create_time', '>=', $today_start],
                ['create_time', '<=', $today_end]
            ])
            ->where('user_id', 'not in', $clerk_user_ids)
            ->select()
            ->toArray();
        
        foreach ($participate_logs as $log) {
            $hour = (int)date('H', strtotime($log['create_time']));
            $participate_data[$hour]++;
        }
        
        // 获取成交人数数据
        $payment_logs = Db::name('order')
            ->where([
                ['activity_id', '=', $activityId],
                ['order_status', '=', 2], // 支付成功
                ['create_time', '>=', $today_start],
                ['create_time', '<=', $today_end]
            ])
            ->where('user_id', 'not in', $clerk_user_ids)
            ->select()
            ->toArray();
        
        foreach ($payment_logs as $log) {
            $hour = (int)date('H', strtotime($log['create_time']));
            $payment_data[$hour]++;
        }
        
        // 返回数据
        return $this->reSuccess('成功', [
            'hours' => $hours,
            'visitor_data' => array_values($visitor_data),
            'join_data' => array_values($join_data),
            'participate_data' => array_values($participate_data),
            'payment_data' => array_values($payment_data)
        ]);
    }

    /**
     * 获取数据大屏 URL
     * @param Request $request
     * @return Response
     */
    public function getUrl(Request $request) : Response
    {
        $activityId = $request->get('activity_id');
        return $this->reSuccess('成功', [
            'url' => getenv('API_HOST').'/api/dashboard/index?code='.urlencode(base64_encode($activityId))
        ]);
    }
}
